import {storeBindingsBehavior} from 'mobx-miniprogram-bindings'
import {getShopDetail, getTags, queryNearbyShopList} from "@src/api/booking";
import base from "@src/store/base";
import location from "@src/store/location";
import router from "@src/router";

Component({
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor', 'perms', 'businessName'],
  }, {
    store: location,
    fields: ['latitude', 'longitude'],
    actions: ['getLocation', 'showAuthTip']
  }],
  data: {
    shopId: null,
    navHeight: 40,
    loading: false,
    shopInfo: null,
    imageList: [],
    tags: null,
    supplyFacility: null,
    supplyService: null,
    fullDayRoomState: 0,
    hourRoomState: 0,
    ktvRoomState: 0,
    navIndex: 0,
    roomNodes: null,
    navBottom: null,
    disableScrollEvent: false,
    scrollNavVisible: false,
    bookingNotes: null,
  },
  methods: {
	onShow(){
	 const pages = getCurrentPages()
	 const currPage = pages[pages.length - 1]
	 console.log('预订---接收门店列表的数据 currPage', currPage.data.storeData)
	 if(currPage.data.storeData){
	  let shopId = currPage.data.storeData.shopId
	  this.setData({shopId})
	  this.fetchData()
	 }
	},
    onLoad(options) {
      let shopId = null;
      if (options.GLOBAL_SHOP_ID) {
        shopId = options.GLOBAL_SHOP_ID;
      }
      if (options.shopId) {
        shopId = options.shopId;
      }
      this.setData({shopId: shopId})
    },
    onLogin() {
      this.getLocation(true).then((res) => {
        if (this.data.shopId) {
          this.setData({latitude: res.latitude, longitude: res.longitude})
          this.fetchData();
        } else {
          this.getNearbyShop(res.latitude, res.longitude);
        }
      }).catch(res => {
        if (this.data.shopId) {
          this.fetchData();
        } else {
          this.getNearbyShop();
        }
      })
    },
    onPullDownRefresh() {
      this.setData({loading: true})
      this.getLocation().then((res) => {
        this.setData({latitude: res.latitude, longitude: res.longitude})
        this.fetchData();
      }).catch(() => {
        this.fetchData();
      })
      setTimeout(() => {
        this.setData({loading: false})
        wx.stopPullDownRefresh();
      }, 300)
    },
    onPageScroll(res) {
      if (!this.data.navBottom || !this.data.roomNodes || this.data.disableScrollEvent) {
        return;
      }
      let scrollTop = res.scrollTop + this.data.navBottom;
      let navIndex = 0;
      let roomNodes = this.data.roomNodes;
      for (let i = 0; i < roomNodes.length; i++) {
        if (scrollTop > roomNodes[i]) {
          navIndex = i;
        }
      }
      let scrollNavVisible = res.scrollTop >= this.data.navBottom;
      if (navIndex === this.data.navIndex && scrollNavVisible === this.data.scrollNavVisible) {
        return;
      }
      this.setData({navIndex: navIndex, scrollNavVisible: res.scrollTop >= this.data.navBottom})
    },
    onShareAppMessage(res) {
      return {
        title: `先预订再到店，方便又便捷，${this.data.businessName}-${this.data.shopInfo.shopName}店欢迎您..`,
        path: `sp-booking/pages/bookingIndex/main?shopId=${this.data.shopId}`,
        desc: "",
        imageUrl: this.data.shareImg
      };
    },
    handlePoster(e) {
      this.setData({"shareImg": e.detail})
    },
    fetchData() {
      let data = {
        shopId: this.data.shopId
      }
      if (this.data.latitude) {
        data.latitude = this.data.latitude;
        data.longitude = this.data.longitude;
      }
      getShopDetail(data).then(res => {
        if (res.code === 0) {
          let data = res.data
          let shopInfo = data.shopInfo
          if (shopInfo.distance) {
            shopInfo.distance = (shopInfo.distance / 1000).toFixed(2)
          }
          this.setData({
            shopInfo: shopInfo,
            imageList: data.imageList,
            supplyFacility: data.supplyFacility,
            supplyService: data.supplyService,
            fullDayRoomState: data.fullDayRoomState,
            hourRoomState: data.hourRoomState,
            ktvRoomState: data.ktvRoomState,
            bookingNotes: data.bookingNotes
          })
          setTimeout(() => {
            this.parseNodes();
          }, 500)

        }
      })
      getTags().then(res => {
        if (res.code === 0) {
          let tagList = res.data;
          if (tagList.length > 0) {
            let tagIdMap = {};
            for (let tag of tagList) {
              tagIdMap[String(tag.id)] = tag.title;
            }
            let tags = {
              list: tagList,
              map: tagIdMap
            }
            this.setData({tags: tags});
          } else {
            this.setData({tags: null});
          }
        }
      })
    },
    getNearbyShop(latitude, longitude) {
      let data = {}
      if (latitude) {
        data['latitude'] = latitude;
        data['longitude'] = longitude;
      }

      queryNearbyShopList(data).then(res => {
        if (res.code === 0) {
          this.setData({'shopId': res.data[0].shopId})
          this.fetchData();
        }
      })
    },
    parseNodes() {
      wx.createSelectorQuery().select(".nav-scroll-container").boundingClientRect(res => {
        if (res) {
          this.setData({navBottom: res.bottom})
        }
      }).exec();
      wx.createSelectorQuery().selectAll(".room-node").boundingClientRect(res => {
        if (!res) {
          return;
        }
        let nodes = [];
        for (let item of res) {
          nodes.push(item.top)
        }
        this.setData({roomNodes: nodes})
      }).exec();
    },
    handleNavTo(e) {
      let index = e.currentTarget.dataset.index;
      this.setData({navIndex: index, disableScrollEvent: true})
      wx.pageScrollTo({
        scrollTop: this.data.roomNodes[index] - this.data.navBottom,
        duration: 300
      })
      setTimeout(() => {
        this.setData({disableScrollEvent: false})
      }, 500)
    },
    handleOpenMap(e) {
      let data = e.currentTarget.dataset.item
      wx.openLocation({
        latitude: data.latitude,
        longitude: data.longitude,
        name: data.name,
        address: data.address
      });
    },
    handleToShopList() {
      router.push({
        name: 'booking/shopList',
        events: {
          'changeShop': (shopId) => {
            if (shopId !== this.data.shopId) {
              this.setData({shopId: shopId, bookingNotes: []})
              this.fetchData();
            }
          }
        }
      })
    }
  }
})
